<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
//use think\console\input\Argument;
//use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;
use \Exception as E;
/**缓存订单写入数据库
 * Class AutomaticDelivery
 * @package app\command
 */
class AutomaticOrder extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('automaticorder')
            ->setDescription('the automaticorder command');
    }

    protected function execute(Input $input, Output $output)
    {
        $flag = false;
        try {
            $getOrderLua = file_get_contents(app()->getAppPath() . 'lua/get_order.lua');
//            while (true) {
                $rtn = Cache::store('redis')->handler()->eval($getOrderLua, [], 0);
                if ($rtn != false) {
//                    if ($rtn != false && $rtn[1] == true) {
                    $orderInfos = $rtn[0];
                    $master = [];
                    $slave = [];
                    foreach ($orderInfos as $orderInfo) {
                        $info = json_decode($orderInfo, true);
                        foreach ($info['order_detal'] as $slaves) {
                            $slave[] = $slaves;
                        }
//                        $slave[] = $info['order_detal'];
                        unset($info['order_detal']);
                        $master[] = $info;
                    }
                    Db::startTrans();
                    $flag = true;
                    $rtn1 = Db::table('eb_order')->insertAll($master);
                    $rtn2 = Db::table('eb_order_detail')->insertAll($slave);
                    if ($rtn1 && $rtn2) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
//                } else {
//                    exit('exit');
//                }
            }
        } catch (E $e) {
            if ($flag) Db::rollback();
            var_dump($e->getMessage());
            exit;
        }
    }
}
